const express = require("express");
const router = express.Router();
const { getDetail } = require("../service/get-detail");
const { result } = require("../util/util");
const { replaceByUrl } = require("../util/upload-by-url");
const stringReplaceAsync = require("string-replace-async");
/**
 * 得到首页分类
 */
router.get("/", async (req, res, next) => {
	try {
		let { id, isReplace } = req.query || {};
		isReplace = Number(isReplace);
		let data = await getDetail({ id });
		let { detail, articles_more } = data.data;
		const translateData = {};
		translateData.audio_src = detail.audio_src;
		if (isReplace) {
			translateData.content = await stringReplaceAsync(
				detail.content,
				/(url\((\S+?)\))|(src=\"(\S*)\")/g,
				async item => {
					let type = "";
					if (/^url\(/.test(item)) {
						type = "URL";
					} else {
						type = "IMG";
					}
					item = item.replace(/(^url\()|(\)$)/g, "");
					item = item.replace(/(^src=")|(\"$)/g, "");
					let img = "";
					try {
						img = await replaceByUrl(item);
					} catch (err) {
						img = item;
						console.log(err);
					}
					return type === "URL" ? `url(${img})` : ` src="${img}"`;
				}
			);
		} else {
			translateData.content = detail.content;
		}
		translateData.share_img = detail.share_img;
		translateData.title = detail.title;
		translateData.shareInfo = articles_more;
		res.json(
			result({
				d: translateData
			})
		);
	} catch (err) {
		console.log(err);
		res.json(
			result({
				s: 0,
				m: err
			})
		);
	}
});

module.exports = router;
